package app.base.systemmanage.systemusersmanage;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataIntegrityViolationException;

import app.base.common.UserSessionInfo;
import app.base.common.Utility;

import app.base.systemmanage.systemusersmanage.dao.SysUsersDAO;
import app.base.systemmanage.systemusersmanage.model.SysUsers;
import app.base.systemmanage.systemusersmanage.model.SysUsersExample;
import app.base.systemmanage.systemusersmanage.model.SysUsersExample.Criteria;

public class SystemUsersHandle extends HttpServlet{

	private static final long serialVersionUID = 1L;
		
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
	    request.setCharacterEncoding(Utility.CHARSET_ENCODING_UTF8);
	    response.setContentType(Utility.DEFAULT_CONTENT_TYPE);

		PrintWriter out = response.getWriter(); 
						
		String cmd = request.getParameter("SYS_OP_CMD");
		
		String result = null;

		if (cmd == null || cmd.trim().length() == 0)
		{
			result = "{returnCode: '-1', msg: '客户端的数据请求命令参数CMD为设置错误'}";
		}
		else
		{
			cmd = cmd.trim();
			
			if (cmd.equals(Utility.SYS_OPERATION_COMMAND_ADD) || cmd.equals(Utility.SYS_OPERATION_COMMAND_MODIFY))
			{
				SysUsers record = new SysUsers();
				
				if (cmd.equals(Utility.SYS_OPERATION_COMMAND_MODIFY))
				{
					record.setUSER_ID(URLDecoder.decode(request.getParameter("USER_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
				}
	
				record.setLOGIN_ID(URLDecoder.decode(request.getParameter("LOGIN_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
				try {
					record.setLOGIN_PWD(Utility.MD5(URLDecoder.decode(request.getParameter("LOGIN_PWD").trim(), Utility.CHARSET_ENCODING_UTF8)).toUpperCase());
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				record.setUSER_TYPE_ID(URLDecoder.decode(request.getParameter("USER_TYPE_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
				record.setUSER_NAME(URLDecoder.decode(request.getParameter("USER_NAME").trim(), Utility.CHARSET_ENCODING_UTF8));
				record.setUSER_DESC(URLDecoder.decode(request.getParameter("USER_DESC").trim(), Utility.CHARSET_ENCODING_UTF8));
				record.setDISPLAY_RANKING_INDEX(BigDecimal.valueOf(Long.valueOf(URLDecoder.decode(request.getParameter("DISPLAY_RANKING_INDEX").trim(), Utility.CHARSET_ENCODING_UTF8))));
				record.setSYS_HOLD_FLAG(URLDecoder.decode(request.getParameter("SYS_HOLD_FLAG").trim(), Utility.CHARSET_ENCODING_UTF8));
				record.setSTATE(URLDecoder.decode(request.getParameter("STATE").trim(), Utility.CHARSET_ENCODING_UTF8));
	
				result = doSystemOperations(request, cmd, record);
			}
			else if (cmd.equals(Utility.SYS_OPERATION_COMMAND_DELETE))
			{
				result = doSystemOperations(request, cmd, URLDecoder.decode(request.getParameter("USER_ID").trim(), Utility.CHARSET_ENCODING_UTF8));
			}
			else
			{
				result = "{returnCode: '-1', msg: '服务器不支持的数据请求命令，请检查后再重试'}";
			}			
			
		}
		
		out.println(result);
		
		out.flush();
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException 
	{
		doGet(request, response);
	}
	
	private String doSystemOperations(HttpServletRequest request, String action, Object o)
	{
		
		String result = "{returnCode: '-1', msg: '系统调用函数 doSystemOperations() 失败'}";
		
		ApplicationContext context = new ClassPathXmlApplicationContext(Utility.DEFAULT_SPRINGFRAMEWORK_APPLICATION_CONTEXT_FILE_PATH);
		SysUsersDAO sysUsersDAO = (SysUsersDAO)context.getBean(Utility.SYSTEM_USERS_MANAGE_MODULE_BEAN_NAME);
		
		String[] perms = null;
		
		if (action.equals(Utility.SYS_OPERATION_COMMAND_ADD))
		{
			perms = new String[]{"PERM_ALL_PERMS", "PERM_SYS_USERMGR_000", "PERM_SYS_USERMGR_001"};
			
			if (!UserSessionInfo.verifyUserPerms(request.getSession(), perms))
			{
				result = "{returnCode: '-1', msg: '用户没有新增操作权限，请联系管理员'}";
			}
			else
			{
				result = insert(sysUsersDAO, (SysUsers) o);
			}
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_MODIFY))
		{
			perms = new String[]{"PERM_ALL_PERMS", "PERM_SYS_USERMGR_000", "PERM_SYS_USERMGR_002"};
			
			if (!UserSessionInfo.verifyUserPerms(request.getSession(), perms))
			{
				result = "{returnCode: '-1', msg: '用户没有修改操作权限，请联系管理员'}";
			}
			else
			{
				result = update(sysUsersDAO, (SysUsers) o);
			}			
		}
		else if (action.equals(Utility.SYS_OPERATION_COMMAND_DELETE))
		{			
			perms = new String[]{"PERM_ALL_PERMS", "PERM_SYS_USERMGR_000", "PERM_SYS_USERMGR_003"};
			
			if (!UserSessionInfo.verifyUserPerms(request.getSession(), perms))
			{
				result = "{returnCode: '-1', msg: '用户没有删除操作权限，请联系管理员'}";
			}
			else
			{
				result = delete(sysUsersDAO, (String) o);
			}				
		}
		
		return result;
	}
	
	private String insert(SysUsersDAO sysUsersDAO, SysUsers record)
	{
		String result = "{returnCode: '0', msg: '新增系统用户成功'}";
		
		try {
			sysUsersDAO.insert_0001(record);		
		} 
		catch(DataIntegrityViolationException e)
		{
			result = "{returnCode: '-1', msg: '系统不允许创建重复的系统用户'}";
		}
		catch (Exception e) {
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}

	private String update(SysUsersDAO sysUsersDAO, SysUsers record)
	{
		String result = "{returnCode: '0', msg: '修改系统用户成功'}";
		
		try {
			sysUsersDAO.update_0001(record);		
		} 		
		catch(DataIntegrityViolationException e)
		{
			result = "{returnCode: '-1', msg: '系统不允许创建重复的多个系统用户'}";
		}
		catch (Exception e) {
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}
	
	private String delete(SysUsersDAO sysUsersDAO, String userId)
	{
		String result = "{returnCode: '0', msg: '删除系统用户成功'}";
		
		try {
			String[] userIds = userId.split("\\" + Utility.SPLIT_CHARS_VERTICAL_LINE);
			
			List<String> usrIds = new ArrayList<String>();
			
			for (int i = 0; i < userIds.length; i++) 
			{
				usrIds.add(userIds[i]);
			}

			SysUsersExample example = new SysUsersExample();
			
			Criteria criteria = example.createCriteria();
			
			criteria.andUSER_IDIn(usrIds);
			
			sysUsersDAO.deleteByExample(example);	
		} 
		catch (DataIntegrityViolationException e) 
		{
			result = "{returnCode: '-1', msg: '删除的用户已经分配角色，请先删除对应的用户角色'}";
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			result = "{returnCode: '-1', msg: " + e.toString() + "'}";
		}
		
		return result;
	}	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}